package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams rep) {
        //创建搜索请求
        SearchRequest hotel = new SearchRequest("hotel");
        SearchSourceBuilder source = hotel.source();
//        buildQurry(rep, source);
        buildBasicQuery(rep,hotel);
        //执行请求
        SearchResponse search = null;
        try {
            search = client.search(hotel, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //响应结果
        SearchHits hits = search.getHits();
        PageResult page = new PageResult();
        page.setTotal(hits.getTotalHits().value);
        List<HotelDoc> docs = new ArrayList<>();
        for (SearchHit sea : hits) {
            String hotelJosn = sea.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(hotelJosn, HotelDoc.class);
            Object[] sortValues = sea.getSortValues();
            if (sortValues != null && sortValues.length > 0) {
                hotelDoc.setDistance(sortValues[0]);
            }
            docs.add(hotelDoc);
        }
        page.setHotels(docs);
        return page;
    }

    private void buildQurry(RequestParams rep, SearchSourceBuilder source) {
        //创建bool查询条件，基于此进行操作
        BoolQueryBuilder bool = QueryBuilders.boolQuery();
        //判断key是否为空并进行操作
        boolean empty = StringUtils.isEmpty(rep.getKey());
        if (empty) {
            source.query(QueryBuilders.matchAllQuery());
        } else {
            source.query(QueryBuilders.matchQuery("all", rep.getKey()));
        }
        source.from((rep.getPage() - 1) * rep.getSize());
        source.size(rep.getSize());
        //city查询
        String city = rep.getCity();
        if (!StringUtils.isBlank(city)) {
            bool.filter(QueryBuilders.termQuery("city", city));
        }
        //startName查询
        String starName = rep.getStarName();
        if (!StringUtils.isBlank(starName)) {
            bool.filter(QueryBuilders.termQuery("startName", starName));
        }
        //品牌查询
        String brand = rep.getBrand();
        if (!StringUtils.isBlank(brand)) {
            bool.filter(QueryBuilders.termQuery("brand", brand));
        }
        //价格查询
        Integer minp = rep.getMinPrice();
        Integer maxp = rep.getMaxPrice();
        if (minp != null && maxp != null) {
            bool.filter(QueryBuilders.rangeQuery("price").gte(minp).lte(maxp));
        }
        //距离排序
        String location = rep.getLocation();
        if (!StringUtils.isBlank(location)) {
            source.sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location)
                    ).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS)
            );
        }

        //算分函数
        FunctionScoreQueryBuilder isAd = QueryBuilders.functionScoreQuery(
                bool,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAd", true),
                                ScoreFunctionBuilders.weightFactorFunction(10))
                }).boostMode(CombineFunction.MULTIPLY);
        source.query(isAd);
}
private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 城市条件
        if (params.getCity() != null && !params.getCity().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        // 品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 星级条件
        if (params.getStarName() != null && !params.getStarName().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        // 价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice())
            );
        }

        // 2.算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });
        request.source().query(functionScoreQuery);
    }
}
